package com.example.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.common.AutoLog;
import com.example.common.JwtTokenUtils;
import com.example.common.Result;
import com.example.entity.*;
import com.example.exception.CustomException;
import com.example.service.GradesService;
import com.example.service.PaperService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/paper")
public class PaperController {
    @Resource
    private PaperService paperService;
    @Resource
    private GradesService gradesService;

    @GetMapping("/search")
    public Result findBySearch(Params params){
        PageInfo<Paper> info = paperService.findBySearch(params);
        return Result.success(info);
    }

    @PostMapping
    @AutoLog("编辑试题")
    public Result save(@RequestBody Paper paper){
        if(paper.getId()==null){
            paperService.add(paper);
        }else{
            paperService.update(paper);
        }
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @AutoLog("删除试题")
    public Result delete(@PathVariable Integer id){
        paperService.delete(id);
        return Result.success();
    }

    @PutMapping("/delBatch")
    @AutoLog("删除试题")
    public Result delBatch(@RequestBody List<Paper> list){
        for(Paper paper : list){
            paperService.delete(paper.getId());
        }
        return Result.success();
    }

    @GetMapping("/export")
    @AutoLog("导出试题")
    public Result export(HttpServletResponse response) throws IOException {
        List<Paper> all = paperService.findAll2();

        if(CollectionUtil.isEmpty(all)){
            throw new CustomException("无数据！");
        }

        List<Map<String,Object>> list = new ArrayList<>();

        for(Paper paper: all){
            Map<String,Object> row = new HashMap<>();
            row.put("paper_text",paper.getPaper_text());
            row.put("paper_type",paper.getPaper_type());
            row.put("typeName",paper.getTypeName());
            row.put("answer",paper.getAnswer());
            list.add(row);
        }

        ExcelWriter wr = ExcelUtil.getWriter(true);

        wr.write(list,true);

        //下载excel
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename=zcy/paper.xlsx");
        ServletOutputStream out = response.getOutputStream();
        wr.flush(out,true);
        wr.close();
        IoUtil.close(System.out);

        return Result.success();
    }

    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException{
        List<Paper> infoList =ExcelUtil.getReader(file.getInputStream()).readAll(Paper.class);
        if(!CollectionUtil.isEmpty(infoList)){
            for(Paper paper: infoList){
                try{
                    Integer typeId =paperService.findTypeId(paper.getTypeName());
                    paper.setTypeId(typeId);
                    paperService.add(paper);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return Result.success();
    }

    @GetMapping("/findPaper")
    public Result findPaper(){
        List<Paper> list = paperService.findAll();
        List<Map<String, Object>> maplist = new ArrayList<>();
        for (Paper paper : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("paperId",paper.getId());
            map.put("title", paper.getPaper_text());
            map.put("img",paper.getImg());
            String paperType = paper.getPaper_type(); // 获取paper类型
            Object options;
            if ("判断".equals(paperType)) {
                options = new String[]{"是", "否"};
            }else{
                options = new String[]{"没有", "轻度", "中度", "重度", "极重"};
            }
            // 将处理后的options放入map中
            map.put("options", options);
//            map.put("answer", paper.getAnswer());
            maplist.add(map);
        }
        return Result.success(maplist);
    }

    @PostMapping ("/examing")
    public Result examing(@RequestBody List<Map<String, Object>> mapList){
        double score=0;double scoreTAS =0;double scoreASLEC =0;
        for (Map<String, Object> userAnswer : mapList) {
            Integer paperId = (Integer) userAnswer.get("paperId");
            String userSelection = (String) userAnswer.get("answer"); // 假设这是用户选择的答案
            Paper paper = paperService.findAnswer(paperId); // 根据题目找到对应的Paper对象
            String paperType = paper.getPaper_type();
            String answer = paper.getAnswer();
            if (paper != null &&userSelection!=null&&"判断".equals(paperType) && userSelection.equals(answer)) {
                scoreTAS++;
            }else if (paper != null&&userSelection!=null&&"选择".equals(paper.getPaper_type())){
                if("没有".equals(paper.getAnswer())){
                    switch (userSelection) {
                        case "没有":
                            scoreASLEC += 4;
                            break;
                        case "轻度":
                            scoreASLEC += 3;
                            break;
                        case "中度":
                            scoreASLEC += 2;
                            break;
                        case "重度":
                            scoreASLEC += 1;
                            break;
                        case "极重":
                            scoreASLEC += 0;
                            break;
                        default:
                            // 处理无效的用户选择
                            break;
                    }
                }else{
                    switch (userSelection) {
                        case "没有":
                            scoreASLEC += 0;
                            break;
                        case "轻度":
                            scoreASLEC += 1;
                            break;
                        case "中度":
                            scoreASLEC += 2;
                            break;
                        case "重度":
                            scoreASLEC += 3;
                            break;
                        case "极重":
                            scoreASLEC += 4;
                            break;
                        default:
                            // 处理无效的用户选择
                            break;
                    }
                }
            }
        }
        Integer numTAS =paperService.findNumber("TAS");
        Integer numASLEC =paperService.findNumber("ASLEC");

        scoreTAS=scoreTAS*100/numTAS;
        scoreASLEC=scoreASLEC*25/numASLEC;

        long roundedScoreTAS = Math.round(scoreTAS);
        long roundedScoreASLEC = Math.round(scoreASLEC);
        //成绩
        scoreTAS*=0.5705;
        scoreASLEC*=0.4295;
        score=scoreTAS+scoreASLEC;

        long roundedScore = Math.round(score);

        System.out.println("你的成绩是"+score+"，TAS是"+scoreTAS+"，ASLEC是"+scoreASLEC);

        Grades grades = new Grades();
        grades.setUserId(JwtTokenUtils.getCurrentUser().getId());
        grades.setGradesTAS((int) roundedScoreTAS);
        grades.setGradesASLEC((int) roundedScoreASLEC);
        grades.setGrades((int) roundedScore);
        gradesService.add(grades);
        return Result.success(roundedScore);
    }
}
